const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const svgCaptcha = require('svg-captcha');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/Blog', {
  useNewUrlParser: true
});
const app = express();

app.use(cookieParser());

app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
      //这段仅仅为了方便返回json而已
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});

const UserSchema = new mongoose.Schema({
  username: {
    type: String,
    unique: true,
  },
  password: {
    type: String
  }
});
const User = mongoose.model('Users', UserSchema);

const db = mongoose.connection;
db.on('error', console.error.bind(console, '数据库连接失败'));
db.once('open', function (){
  console.log('数据库连接成功');

  //注册
  app.get('/api/register', function (req, res, next) {
    const username = req.query.username;
    const password = req.query.password;
    User.find({username: username}, function (err, doc) {
      if (err) {
        throw err;
      }else {
        if (doc.length !== 0) {
          res.send({
            msg: '该用户已存在',
            code: 301
          });
        }else {
          const userCase = new User({
            username: username,
            password: password
          });
          userCase.save(function (err, doc) {
            if (err) {
              res.send({
                msg: '注册失败',
                code: 300
              });
            }else {
              res.send({
                msg: '注册成功',
                code: 200
              });
            }
          });
        }
      }
    });
  });
  //登录
  app.get('/api/login', function (req, res, next) {
    const username = req.query.username;
    const password = req.query.password;
    User.find({username: username, password: password}, function (err, doc) {
      if (err) throw err;
      console.log(doc);
      if (doc.length === 0) {
        res.send({
          code: 301,
          msg: '用户名不存在或密码错误'
        });
      }else {
        res.send({
          code: 200,
          msg: '登录成功'
        });
      }
    })
  });
  //修改密码
  app.get('/api/updatePassword', function (req, res, next) {
    const username = req.query.username;
    const password = req.query.password;
    User.updateOne({username: username}, {password: password}, function (err, doc) {
      if (err) throw err;
      console.log(doc);
      if (doc.n === 0) {
        res.send({
          code: 301,
          msg: '用户名不存在'
        });
      }else if (doc.nModified === 0) {
        res.send({
          code: 302,
          msg: '密码不能与原来相同'
        });
      }else if (doc.ok === 0) {
        res.send({
          code: 303,
          msg: '修改失败'
        });
      }else {
        res.send({
          code: 200,
          msg: '修改成功'
        });
      }
    })
  });
});

app.get('/api/getCaptcha', function (req, res, next) {
  const captcha = svgCaptcha.create({ 
    // 翻转颜色 
    inverse: false, 
    // 字体大小 
    fontSize: 36, 
    // 噪声线条数 
    noise: 2, 
    // 宽度 
    width: 80, 
    // 高度 
    height: 30, 
   });
  req.session = captcha.text.toLowerCase(); 
  console.log(req.session); //0xtg 生成的验证码
  //保存到cookie 方便前端调用验证
  res.cookie('captcha', req.session); 
  res.setHeader('Content-Type', 'image/svg+xml');
  res.write(String(captcha.data));
  res.end();
});

app.listen('8080', function (){
  console.log('服务已启动');
})